
import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import Drawer from '@/components/drawer/Index'
import FilterRender from '@/render/FilterRender'
import renderModal, {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import type {
    PeriodInsuranceMaterialsDto,
    InsuranceMaterialsFileDto,
    LongInsuranceCaseListDto,
    ReportCaseResultDto
} from '@/api/insurance/period/types'
import { addPeriodInsuranceMaterials, removePeriodInsuranceMaterials,exportPeriodInsuranceMaterials, addDailyInsuranceMaterials, removeDailyInsuranceMaterials, exportDailyInsuranceMaterials } from '@/api/insurance/period/index'
import { wait, downloadBlobString } from '@/utils/util'
import { nextTick } from 'vue'
import { Button } from 'ant-design-vue'
@Component
export class SetMaterialPopView extends FilterRender {
    uploadChangeKey = ''
    @Prop() show!: boolean
    @Prop() previewList!: PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>[]
    @Prop() type!: string
    @Prop() basicInfo!: LongInsuranceCaseListDto<ReportCaseResultDto>
    showDrawer = false


   @Emit('update:show')
    updateShow(val: boolean) {
        return val
    }

    @Emit('change')
   handleChange() {
       return 
   }

    @Watch('show', { immediate: true })
    handleWatchShow() {
        this.showDrawer = this.show
    }

    @Watch('showDrawer', { immediate: true })
    handleWatchShowDialog() {
        this.updateShow(this.showDrawer)
    }

    @Watch('previewList', { immediate: true, deep: true })
    handleWatchPreviewList(nav:PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>[]) {
        nav.forEach(item => { 
            this.formConfig.items[item.type] = {
                name: `(${ item.name} ${item.files.length}/3)`,
                element: 'upload',
                value: item.files.map((ite:InsuranceMaterialsFileDto) => { 
                    return {
                        url: ite.fileUrl,
                        fileId: ite.fileId
                    }
                }),
                multiple: true,
                
                params: {
                    autoUpload: false,
                    base64: true,
                    type: 'text',
                    accept: '.png,.jpg,.jpeg',
                    suffix: item.detail,
                    isCurrent: true,
                    limit: 3
                },
                callback: {
                    change: this.onUploadChange
                },
                required: true
            }
        })
        console.log(this.formConfig, 'this.formConfig')
    }
    // 上传方法
    async onUploadChange(event: { current: {fileId:number, base64: string, uid: number,operationType:string }, fileList: { url: string, base64: string, uid: number }[] }) {
        await wait(300)
        const { current, fileList } = event
        console.log(current, 'currentcurrentcurrent')
        if (current.operationType === 'add') {
            await this.getKeyByUid(current.uid)
            if (this.type === 'period') {
                await addPeriodInsuranceMaterials({
                    companyId: this.basicInfo.companyId,
                    categoryType: Number(this.uploadChangeKey),
                    file: current.base64.replaceAll('data:image/jpeg;base64,', ''),
                    reportCaseId: Number(this.basicInfo.id)
                })
            } else { 
                await addDailyInsuranceMaterials({
                    companyId: this.basicInfo.companyId,
                    categoryType: Number(this.uploadChangeKey),
                    file: current.base64.replaceAll('data:image/jpeg;base64,', ''),
                    reportCaseId: Number(this.basicInfo.id)
                })
            }
        } else if (current.operationType === 'delete') { 
            console.log('触发了吗')
            if (this.type === 'period') {
                await removePeriodInsuranceMaterials(current.fileId)
            } else {
                console.log(current.fileId,'删除')
                await removeDailyInsuranceMaterials(current.fileId)
            }			
        }
        this.handleChange()
    }
    // 根据uid知道对象的key
    async getKeyByUid(uid: number) { 
        // await nextTick()
        await wait(100)
        const params = getModelValue(this.formConfig)
        for (const key in params) {
            params[key].forEach((item: { uid: number }) => { 
                if (uid === item.uid) { 
                    this.uploadChangeKey = key
                }
            })
        }
    }
    
    formConfig = this.initFormConfig() as FormModalDto
    initFormConfig() { 
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: true,
            items: {
                // voucherUrl: {
                //     name: '门诊病历(0/3)',
                //     element: 'upload',
                //     params: {
                //         autoUpload: false,
                //         base64: true,
                //         type: 'text',
                //         accept: '.png,.jpg,.jpeg',
                //         multiple: 3,
                //         suffix:'首诊病历，复诊病历，需医院盖章'
                //     },
                // }
            },
            complete: async () => {
                // const data = getModelValue(this.basicFormConfig)
            },
            cancel: () => {
                // this.basicFormConfig.show = false
            },
        } as FormModalDto
    } 
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }
    // 导出材料
    async onExportInsuranceMaterials() {
        if (this.type === 'period') {
            const result = await exportPeriodInsuranceMaterials({
                reportCaseId: Number(this.basicInfo.id),
                insureCompany: this.basicInfo.insurCompany
            })
            await downloadBlobString(result,'长期保保险材料','zip')
        } else {
            const result = await exportDailyInsuranceMaterials({
                reportCaseId: Number(this.basicInfo.id),
                insureCompany: this.basicInfo.insureCompanyType
            })
            await downloadBlobString(result,'日保保险材料','zip')
        }
    }
    created() { 
        this.basicForm = renderForm(this.formConfig)
    }
    render() {
        return (
            <>
                {/* {this.renderFilter()} */}
                {/* Drawer 组件暂时不可用 */}
				
                {/* <Drawer v-model={this.showDrawer} title="上传资料" size="700" height="100%">
                    <div>
                        { this.basicForm.element() }
                    </div>
                    <div class="w-full flex items-center justify-center">
                        <Button type="primary" onClick={this.onExportInsuranceMaterials}>导出</Button>
                    </div>
                </Drawer> */}
            </>
        )
    }
}

export default toNative<{previewList:PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>[],type:string,basicInfo: LongInsuranceCaseListDto<ReportCaseResultDto>}, {change: () => void}>(SetMaterialPopView)